package com.kevin;

import com.kevin.Entity.Header;
import com.kevin.Entity.MessageRecord;
import com.kevin.Entity.OptCode;
import com.kevin.serial.MessageRecordEncoder;
import com.kevin.serial.MessageRecorderDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class NettyProtocolClient {

    public static void main(String[] args) {

        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
        bootstrap.group(eventLoopGroup);
        bootstrap.channel(NioSocketChannel.class)
                .handler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(
                                Integer.MAX_VALUE,
                                9,
                                4,
                                0,
                                0))
                                .addLast(new MessageRecordEncoder())
                                .addLast(new MessageRecorderDecoder())
                                .addLast(new ChannelInboundHandlerAdapter(){
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        MessageRecord messageRecord = (MessageRecord)msg;
                                        System.out.println("client recieve msg:"+messageRecord.toString());
                                    }
                                });
                    }
                });
        try {
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1",8080).sync();
            Channel channel = channelFuture.channel();
            for(int i=0;i<2;i++){
                MessageRecord messageRecord = new MessageRecord();
                Header header = new Header();
                header.setSessionId(123);
                header.setOptCode(OptCode.OPT_REQ.getCode());
                String content = "客户端发来数据："+i;
                header.setBodyLength(content.length());
                messageRecord.setHeader(header);
                messageRecord.setBody(content);
                channel.writeAndFlush(messageRecord);
            }
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        finally {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
